package com.innerchic.huhu.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：young
 * 日    期：2021/11/4 15:31
 * 包    名：com.innerchic.huhu.tool
 * 描    述：算法
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */
public class Arithmetic {

    /**
     * 原始码集合
     */
    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

    /**
     * 获取md5值
     *
     * @param input 输入内容
     * @return md5
     * @throws NoSuchAlgorithmException 找不到算法解释器md5
     */
    public static String md5(String input) throws NoSuchAlgorithmException {
        byte[] bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
        return printHexBinary(bytes);
    }

    public static String md5(File file) {
        FileInputStream in = null;
        MessageDigest digest = null;
        byte[] buffer = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return printHexBinary(digest.digest());
    }

    /**
     * 获取md5值-大写
     *
     * @param input 输入内容
     * @return md5大写
     * @throws NoSuchAlgorithmException 找不到算法解释器md5
     */
    public static String md5Upper(String input) throws NoSuchAlgorithmException {
        return md5(input).toUpperCase();
    }

    public static String printHexBinary(byte[] data) {
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

}
